using MediatR;
using Medical.Api.Read.Application.Command.BasicManagement.ShelfDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Read.Application.Handler.BasicManagement.ShelfDictionaryHandler
{
    /// <summary>
    /// 货架查询处理器
    /// </summary>
    public class QueryShelvesHandler : IRequestHandler<QueryShelvesCommand, ApiResult<ApiPageIng<Shelves>>>
    {
        private readonly IBaseRepository<Shelves> _shelvesRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="shelvesRepository">货架仓储接口</param>
        public QueryShelvesHandler(IBaseRepository<Shelves> shelvesRepository)
        {
            _shelvesRepository = shelvesRepository;
        }

        /// <summary>
        /// 处理货架查询请求
        /// </summary>
        public Task<ApiResult<ApiPageIng<Shelves>>> Handle(QueryShelvesCommand request, CancellationToken cancellationToken)
        {
            var query = _shelvesRepository.GetAll().Where(x => !x.IsDeleted);

            // 根据上级货架ID筛选
            if (request.QueryDto.ParentShelfId.HasValue)
            {
                query = query.Where(x => x.ParentShelfId == request.QueryDto.ParentShelfId);
            }

            // 根据状态筛选
            if (request.QueryDto.Status.HasValue)
            {
                query = query.Where(x => x.Status == request.QueryDto.Status);
            }

            // 分页查询
            var totalCount = query.Count();
            var items = query
                .Skip((request.QueryDto.PageIndex - 1) * request.QueryDto.PageSize)
                .Take(request.QueryDto.PageSize)
                .ToList();

            return Task.FromResult(new ApiResult<ApiPageIng<Shelves>>
            {
                Code = ApiEnums.Success,
                Msg = "货架列表查询成功",
                Data = new ApiPageIng<Shelves>
                {
                    PageData = items,
                    TotalCount = totalCount,
                }
            });
        }
    }
}